package com.jxzn.locust.model;

import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.Transient;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import org.springframework.util.DigestUtils;

import com.jxzn.locust.support.Auth;
import com.jxzn.locust.support.Module;
import com.jxzn.locust.support.OperateAction;

import lombok.Data;
import lombok.EqualsAndHashCode;

@Data
@EqualsAndHashCode(callSuper = false)
@Entity
@DynamicInsert
@DynamicUpdate
public class SysResource extends AbstractNamedModel implements Comparable<SysResource> {
    /**
    * 
    */
    private static final long serialVersionUID = 1L;
    /** 资源的唯一标识符 */
    String uuid;
    /** 模块 */
    String module;
    /** 操作 */
    @Enumerated(EnumType.STRING)
    OperateAction operation;

    @Transient
    boolean selected;

    public SysResource() {
        super();
    }

    public SysResource(Module module, Auth auth) {
        super();
        this.module = module.value();
        this.operation = auth.action();
        this.name = StringUtils.defaultIfEmpty(auth.value(), auth.action().getName());
        this.uuid = getKey();
    }

    public String getKey() {
        return DigestUtils.md5DigestAsHex(getValue().getBytes());
    }

    public String getValue() {
        return this.module + "_" + this.name + "_" + this.operation;
    }

    public String getSessionKey() {
        return this.module + "_" + this.operation;
    }

    @Override
    public int compareTo(SysResource o) {
        return Integer.valueOf(operation.ordinal()).compareTo(Integer.valueOf(o.getOperation().ordinal()));
    }
}
